package com.xing.controller;

import com.alibaba.fastjson.JSON;
import com.xing.entity.pojo.Article;
import com.xing.entity.pojo.ArticleType;
import com.xing.entity.pojo.SystemUser;
import com.xing.entity.vo.AjaxMessage;
import com.xing.entity.vo.ArticlePage;
import com.xing.service.ArticleService;
import com.xing.service.ArticleTypeService;
import com.xing.service.SystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/article")
public class ArtilcleController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private ArticleTypeService articleTypeService;
    @Autowired
    private SystemUserService systemUserService;

    @ResponseBody
    @RequestMapping("/findById")
    public String findArticleById(){
        Article article =  articleService.selectByPrimaryKey("6");
        return JSON.toJSONString(article);
    }


    @RequestMapping("/findArticleAll")
    public String  findByPage(Model model,
                              @RequestParam(value = "currentPage",required = false,defaultValue = "1") Integer currentPage,
                              @RequestParam(value = "rows",required = false,defaultValue = "3") Integer rows,
                              @RequestParam(value = "typeName",required = false) String typeName,
                              @RequestParam(value = "newsState",required = false,defaultValue = "-1") byte newsState,
                              @RequestParam(value = "type",required = false)String type){

            ArticlePage page = articleService.findByPage(currentPage, rows,typeName,newsState);

        model.addAttribute("page",page);
        model.addAttribute("typeName",typeName);
        model.addAttribute("newsState",newsState);
        if(type!=null){
            model.addAttribute("type",type);
        }
        return "list";
    }




    @RequestMapping("/findByArticle/{id}/{currentPage}/{rows}")
    public String findByArticle(Model model, @PathVariable(value = "id") String articleid, @PathVariable("currentPage")Integer currentPage,@PathVariable("rows") Integer rows){
        model.addAttribute("currentPage",currentPage);
        model.addAttribute("rows",rows);
        List<ArticleType> types = articleTypeService.findAll();
        model.addAttribute("types",types);
        if(articleid.equals("add")){
            return "addArticle";
        }else {
            System.out.println(articleid);
            Article article = articleService.selectByPrimaryKey(articleid);
            model.addAttribute("article",article);
            return "updateArticle";
        }
    }


    @GetMapping("/findByTitle")
    @ResponseBody
    public Boolean findByTitle(String title){
        Article titleId = articleService.findByTitle(title);
        if(titleId!=null){
            return false;
        }else {
            return true;
        }
    }



    @RequestMapping("/deleteArticle/{id}/{currentPage}/{rows}")
    public String deleteArticle(@PathVariable("id")  String articleId,@PathVariable("currentPage")Integer currentPage,@PathVariable("rows") Integer rows){
        articleService.deleteByPrimaryKey(articleId);
        return "redirect:/article/findArticleAll?currentPage="+currentPage+"&rows="+rows+"";
    }


    @RequestMapping("/deleteSelectedArticle")
    @ResponseBody
    public String deleteSelectedArticle(@RequestParam("ids")  String[] ids){
        String msg;
        Boolean aBoolean = articleService.deleteckArticle(ids);
        if(aBoolean){
            msg="删除成功！";
        }else {
            msg="删除失败！";
        }
        return msg;
    }

    @PostMapping("/addAjaxArticle")
    @ResponseBody
    public AjaxMessage fileUploadAdd(@Valid Article article, BindingResult bindingResult,
                                     @RequestParam(value = "file",required = false) MultipartFile multipartFile,
                                     HttpServletRequest request,HttpSession session) {
        if(bindingResult.hasErrors()) {
            List<FieldError> errors = bindingResult.getFieldErrors();
//            for (FieldError error : errors) {
//                error.getDefaultMessage();
//                error.getField();
//
//            }
            return new AjaxMessage().setSuccess(false).setCode(100).setMessage("验证失败").addDetail("errors",errors);
        }
        return articleService.fileUploadAdd(article,multipartFile,request,session);
    }

    @PostMapping("/updateAjaxArticle")
    @ResponseBody
    public AjaxMessage updataAjaxArticle(@Valid Article article, BindingResult bindingResult,
                                     @RequestParam(value = "file",required = false) MultipartFile multipartFile,
                                     HttpServletRequest request) {
        if(bindingResult.hasErrors()) {
            List<FieldError> errors = bindingResult.getFieldErrors();
            return new AjaxMessage().setSuccess(false).setCode(100).setMessage("验证失败").addDetail("errors",errors);
        }
        return articleService.updataAjaxArticle(article,multipartFile,request);
    }

    @RequestMapping("/goDetailed/{articleId}/{currentPage}/{rows}")
    public String goDetailed(@PathVariable("articleId") String articleId,Model model,@PathVariable("currentPage")Integer currentPage,@PathVariable("rows") Integer rows){
        Article article = articleService.selectByPrimaryKey(articleId);
        SystemUser user = systemUserService.selectByPrimaryKey(article.getUserId());
        ArticleType type = articleTypeService.selectByPrimaryKey(article.getTypeId());
        model.addAttribute("article",article);
        model.addAttribute("user",user);
        model.addAttribute("type",type);
        model.addAttribute("currentPage",currentPage);
        model.addAttribute("rows",rows);
        return "detailed";
    }


}
